package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)

// 定义一个结构体表示server
type Server struct {
	Ip        string
	Port      int
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	Message   chan string
}

// 创建server实例并返回一个指针
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

func (server *Server) ListenMessage() {
	for {
		msg := <-server.Message
		//将消息发送给所有在线用户
		server.mapLock.Lock()
		for _, cli := range server.OnlineMap {
			cli.C <- msg
		}
		server.mapLock.Unlock()
	}
}

// 用户上线消息发送到广播管道中
func (server *Server) BroadCastUser(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	server.Message <- sendMsg
}

func (server *Server) Handler(conn net.Conn) {
	//用户上线
	user := NewUser(conn, server)
	user.Online()
	active := make(chan bool)
	//监听用户发送的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			
			n, err := conn.Read(buf)
			if n == 0 {
				user.offline()
				return
			}

			if err != nil && err != io.EOF {
				fmt.Println("conn read err :", err)
				return
			}
			msg := string(buf[:n-1])

			user.doMessage(msg)
			//表示用户活跃
			active <- true
		}
	}()
	//当前handler阻塞
	for {
		select {
		case <-active:
			//表示当前用户活跃，不做任何事情，为了更新下面的计时器

		case <-time.After(time.Second * 300):
			//已经超时
			fmt.Println(user.Name + " out of time offline")
			user.sendMsg("out of time offline")
			user.Server.mapLock.Lock()
			delete(user.Server.OnlineMap,user.Name)
			user.Server.mapLock.Unlock()
			close(user.C)
			conn.Close()
			return
		}
	}

}

func (server *Server) Start() {
	//创建socket
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", server.Ip, server.Port))
	if err != nil {
		fmt.Println("net.Listen err:", err)
		return
	}
	//方法运行完毕后关闭连接
	defer listener.Close()

	//监听广播消息，并发送给所有在线用户
	go server.ListenMessage()

	for {
		//建立连接，也就是代表用户上线了
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("listener err :", err)
		}
		go server.Handler(conn)
	}
}
